import axios from "axios";
const API_KEY = 'Yup2My0PjP23xjXkkCQF0Mzi';
const SECRET_KEY = 'oK5tn5CkgEGyIwRxxxtqUEvldGUaJgSd';
const ACCESS_TOKEN_URL = `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${API_KEY}&client_secret=${SECRET_KEY}`;
const CHAT_API_URL = 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro';

// 直接获取token
const getAccessToken = async () => {
  try {
    console.log('开始获取token...');
    const response = await axios({
      url: ACCESS_TOKEN_URL,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Accept': '*/*'
      }
    });
    console.log('获取token响应:', response.data);
    return response.data.access_token;
  } catch (error) {
    console.error('获取token失败:', error.message);
    throw error;
  }
};

// 测试token是否有效
const testToken = async (token) => {
  try {
    console.log('开始测试token...');
    const response = await axios({
      url: `${CHAT_API_URL}?access_token=${token}`,
      method: 'POST',
      data: {
        messages: [{
          role: 'user',
          content: '赣傩文化是什么'
        }],
        temperature: 0.95,
        top_p: 0.8,
        penalty_score: 1,
        enable_system_memory: false,
        disable_search: false,
        enable_citation: false
      },
      header: {
        'Content-Type': 'application/json',
        'Accept': '*/*'
      }
    });
    console.log('测试响应:', response.data);
    return response.data;
  } catch (error) {
    console.error('测试token失败:', error.message);
    throw error;
  }
};

// 运行完整测试
const runTest = async () => {
  try {
    // 1. 获取token
    console.log('=== 开始获取token ===');
    const token = await getAccessToken();
    console.log('获取到的token:', token);
    console.log('token长度:', token.length);
    console.log('\n');

    // 2. 测试token
    if (token) {
      console.log('=== 开始测试token ===');
      const result = await testToken(token);
      console.log('测试结果:', result);
      console.log('\n');
    }

    return {
      success: true,
      token,
      testTime: new Date().toISOString()
    };
  } catch (error) {
    return {
      success: false,
      error: error.message,
      testTime: new Date().toISOString()
    };
  }
};

// 执行测试
console.log('开始执行测试...\n');
runTest()
  .then(result => {
    console.log('=== 测试完成 ===');
    console.log(JSON.stringify(result, null, 2));
    process.exit(0);
  })
  .catch(error => {
    console.error('测试失败:', error);
    process.exit(1);
  }); 